<template>
  <base-table-layout
    title="物资出库管理"
    :total="total"
    :current-page="currentPage"
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-select
        v-model="searchForm.materialId"
        placeholder="选择物资"
        style="width: 200px;"
        clearable
        class="filter-item"
      >
        <el-option
          v-for="item in materialList"
          :key="item.materialId"
          :label="item.materialName"
          :value="item.materialId"
        />
      </el-select>
      <el-select
        v-model="searchForm.deptId"
        placeholder="选择仓库"
        style="width: 200px;"
        clearable
        class="filter-item"
      >
        <el-option
          v-for="item in departmentList"
          :key="item.deptId"
          :label="item.deptName"
          :value="item.deptId"
        />
      </el-select>
      <el-select
        v-model="searchForm.releaseType"
        placeholder="出库类型"
        style="width: 200px;"
        class="filter-item"
      >
        <el-option label="领用" :value="1" />
        <el-option label="调拨" :value="2" />
        <el-option label="报废" :value="3" />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="resetSearch"
      >重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-minus"
        @click="handleAdd"
      >出库</el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete"
      >批量删除</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="56"
        />
        <el-table-column prop="releaseId" label="出库ID" />
        <el-table-column prop="materialId" label="物资名称" width="200">
          <template slot-scope="scope">
            {{ getMaterialName(scope.row.materialId) }}
          </template>
        </el-table-column>
        <el-table-column prop="deptId" label="仓库名称" width="200">
          <template slot-scope="scope">
            {{ getDepartmentName(scope.row.deptId) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="出库数量" width="95" align="right" />
        <el-table-column prop="releaseType" label="出库类型" width="95">
          <template slot-scope="scope">
            <el-tag
              :type="getReleaseTypeStyle(scope.row.releaseType)"
              size="medium"
            >
              {{ getReleaseTypeLabel(scope.row.releaseType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="releaseTime" label="出库时间" width="180" />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="remark" label="备注" min-width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="!scope.row.remark">-</span>
            <span v-else-if="scope.row.remark.length <= 20">{{ scope.row.remark }}</span>
            <el-button v-else type="text" @click="showRemarkDialog(scope.row.remark)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" >
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 新增/编辑出库对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
        <el-form :model="releaseForm" :rules="rules" ref="releaseForm" label-width="100px">
          <div class="form-row">
            <el-form-item label="物资名称" prop="materialId">
              <el-select 
                v-model="releaseForm.materialId" 
                placeholder="请选择物资" 
                style="width: 100%" 
                @change="handleMaterialChange"
                :disabled="dialogTitle === '编辑出库记录'"
              >
                <el-option v-for="item in materialList" :key="item.materialId" :label="item.materialName" :value="item.materialId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="仓库" prop="deptId">
              <el-select 
                v-model="releaseForm.deptId" 
                placeholder="请选择仓库" 
                style="width: 100%" 
                @change="handleDepartmentChange"
                :disabled="dialogTitle === '编辑出库记录'"
              >
                <el-option v-for="item in departmentList" :key="item.deptId" :label="item.deptName" :value="item.deptId"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="form-row">
            <el-form-item label="出库数量" prop="quantity">
              <el-input-number 
                v-model="releaseForm.quantity" 
                :min="1" 
                style="width: 100%"
                :disabled="dialogTitle === '编辑出库记录'"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="出库类型" prop="releaseType">
              <el-select v-model="releaseForm.releaseType" placeholder="请选择出库类型" style="width: 100%">
                <el-option label="领用" :value="1" />
                <el-option label="调拨" :value="2" />
                <el-option label="报废" :value="3" />
              </el-select>
            </el-form-item>
          </div>
          <div class="form-row">
            <el-form-item label="出库时间" prop="releaseTime">
              <el-date-picker
                v-model="releaseForm.releaseTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="操作人" prop="operator">
              <el-input v-model="releaseForm.operator"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="releaseForm.remark" rows="3" maxlength="500" show-word-limit></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 备注详情弹窗 -->
      <el-dialog
        title="备注详情"
        :visible.sync="remarkDialogVisible"
        width="30%"
      >
        <span style="word-break: break-all;">{{ currentRemark }}</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="remarkDialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'MaterialRelease',
  components: {
    BaseTableLayout
  },
  data() {
    return {
      loading: false,
      searchForm: {
        materialId: undefined,
        deptId: undefined,
        releaseType: undefined,
        releaseTime: undefined
      },
      materialList: [],
      departmentList: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      remarkDialogVisible: false,
      currentRemark: '',
      releaseForm: {
        materialId: undefined,
        deptId: undefined,
        quantity: 1,
        releaseType: 1,
        releaseTime: undefined,
        operator: '',
        remark: ''
      },
      rules: {
        materialId: [
          { required: true, message: '请选择物资', trigger: 'change' }
        ],
        deptId: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入出库数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
        ],
        releaseType: [
          { required: true, message: '请选择出库类型', trigger: 'change' }
        ],
        releaseTime: [
          { required: true, message: '请选择出库时间', trigger: 'change' }
        ],
        operator: [
          { required: true, message: '请输入操作人', trigger: 'blur' }
        ]
      },
      selectedRows: []
    }
  },
  methods: {
    showRemarkDialog(remark) {
      this.currentRemark = remark
      this.remarkDialogVisible = true
    },

    getReleaseTypeLabel(type) {
      const typeMap = {
        1: '领用',
        2: '调拨',
        3: '报废'
      }
      return typeMap[type] || '未知类型'
    },

    getReleaseTypeStyle(type) {
      const styleMap = {
        1: 'success',  // 绿色
        2: 'warning',  // 黄色
        3: 'danger'    // 红色
      }
      return styleMap[type]
    },

    async handleLoadData() {
      try {
        this.loading = true
        const response = await request.get('/material/release/page', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            ...this.searchForm
          }
        })
        
        this.tableData = response.records
        this.total = response.total
      } catch (error) {
        console.error('获取出库数据失败:', error)
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    handleSearch: _.debounce(async function() {
      this.currentPage = 1
      await this.handleLoadData()
    }, 300),

    async resetSearch() {
      this.searchForm = {
        materialId: undefined,
        deptId: undefined,
        releaseType: undefined,
        releaseTime: undefined
      }
      this.currentPage = 1
      await this.handleLoadData()
    },

    handleAdd() {
      this.dialogTitle = '新增出库记录'
      this.releaseForm = {
        materialId: undefined,
        deptId: undefined,
        quantity: 1,
        releaseType: 1,
        releaseTime: undefined,
        operator: '',
        remark: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = '编辑出库记录'
      this.releaseForm = { 
        ...row,
        materialId: Number(row.materialId),
        deptId: Number(row.deptId),
        quantity: Number(row.quantity)
      }
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该出库记录吗？', '提示', {
          type: 'warning'
        })
        await request.delete(`/material/release/${row.releaseId}`)
        this.$message.success('删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('删除失败:', error)
          this.$message.error(error.response?.data?.message || '删除失败')
        }
      }
    },

    handleSelectionChange(val) {
      this.selectedRows = val
    },

    async handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的出库记录')
        return
      }

      try {
        await this.$confirm('确认删除选中的出库记录吗？', '提示', {
          type: 'warning'
        })
        const releaseIds = this.selectedRows.map(row => Number(row.releaseId))
        await request.delete('/material/release/batch', {
          data: releaseIds
        })
        this.$message.success('批量删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('批量删除失败:', error)
          this.$message.error(error.response?.data?.message || '批量删除失败')
        }
      }
    },

    async handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      await this.handleLoadData()
    },

    async handleCurrentChange(val) {
      this.currentPage = val
      await this.handleLoadData()
    },

    async submitForm() {
      try {
        const valid = await this.$refs.releaseForm.validate()
        if (!valid) return

        const submitData = {
          ...this.releaseForm,
          materialId: Number(this.releaseForm.materialId),
          deptId: Number(this.releaseForm.deptId),
          quantity: Number(this.releaseForm.quantity),
          releaseType: Number(this.releaseForm.releaseType)
        }

        if (this.releaseForm.releaseId) {
          await request.put('/material/release', submitData)
          this.$message.success('更新成功')
        } else {
          await request.post('/material/release', submitData)
          this.$message.success('添加成功')
        }
        
        this.dialogVisible = false
        await this.handleLoadData()
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error(error.response?.data?.message || '保存失败，请稍后重试')
      }
    },

    async getMaterialList() {
      try {
        const response = await request.get('/material/materialAll')
        if (Array.isArray(response)) {
          this.materialList = response.map(item => ({
            materialId: Number(item.materialId),
            materialName: item.materialName || '未知物资'
          }))
        } else {
          console.error('获取物资列表格式异常')
          this.materialList = []
        }
      } catch (error) {
        console.error('获取物资列表失败:', error)
        this.materialList = []
      }
    },

    getMaterialName(materialId) {
      if (!materialId || !this.materialList || this.materialList.length === 0) {
        return '未知物资'
      }
      const material = this.materialList.find(item => Number(item.materialId) === Number(materialId))
      return material ? material.materialName : '未知物资'
    },

    async getDepartmentList() {
      try {
        const response = await request.get('/departments/page', {
          params: {
            current: 1,
            size: 100,
            deptType: 5  // 仓库类型
          }
        })
        if (response && response.records) {
          this.departmentList = response.records.map(item => ({
            deptId: Number(item.deptId),
            deptName: item.deptName || '未知仓库'
          }))
        } else {
          console.error('获取仓库列表格式异常')
          this.departmentList = []
        }
      } catch (error) {
        console.error('获取仓库列表失败:', error)
        this.departmentList = []
      }
    },

    getDepartmentName(deptId) {
      if (!deptId || !this.departmentList || this.departmentList.length === 0) {
        return '未知仓库'
      }
      const department = this.departmentList.find(item => Number(item.deptId) === Number(deptId))
      return department ? department.deptName : '未知仓库'
    },

    handleDepartmentChange(value) {
      this.releaseForm.deptId = Number(value)
    },

    handleMaterialChange(value) {
      this.releaseForm.materialId = Number(value)
    }
  },
  created() {
    this.handleLoadData()
    this.getMaterialList()
    this.getDepartmentList()
  }
}
</script>

<style lang="scss" scoped>
.form-row {
  display: flex;
  gap: 20px;
  
  .el-form-item {
    flex: 1;
  }
}

.dialog-footer {
  text-align: right;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>
